<?php
/**
 * @desc    自定义缓存类
 * @author  lijianwei
 */
class DiyCache{//重命名为DiyCache 防止和ThinkPHP\Lib\Think\Util\Cache.class.php重名
  public $cache_dir;
  public $is_cached;
  public $cache_filename;
  public function __construct($cache_dir=""){
	 if(empty($cache_dir)){
		 $this->cache_dir=(substr(HTML_PATH,-1)=="/")?substr(HTML_PATH,0,-1):HTML_PATH;
	 }else{
		$this->cache_dir=$cache_dir; 
	 }
  }
  //约定用 MODULE_NAME  ACTION_NAME  $_GET 作为缓存界定
  public function is_cached(){
	if(!C("diy_cache")) return false;
	$m=strtolower(MODULE_NAME);
	$a=strtolower(ACTION_NAME);
	
	if(!empty($_GET)){
		asort($_GET);
		$param=$m."-".$a."-".implode("-",array_keys($_GET))."-".implode("-",array_values($_GET));
	}else{
		$param=$m."-".$a;
	}
	$cache_name=$m."_".$a."_".sprintf("%X",crc32($param));
	$hash_dir=substr(md5($cache_name),0,1);
	if(!is_dir($this->cache_dir."/".$hash_dir))@mkdir($this->cache_dir."/".$hash_dir);
	
	$this->cache_filename=$this->cache_dir."/".$hash_dir."/".$cache_name.C("HTML_FILE_SUFFIX");
	if(!is_file($this->cache_filename)){
		$this->cached=false;
		return false;
	}else{
		$this->cached=true;
		if(C("HTML_READ_TYPE")==0){
		   echo @file_get_contents($this->cache_filename);
		   exit;
		}else if(C("HTML_READ_TYPE")==1){
		   redirect(str_replace(array(realpath($_SERVER["DOCUMENT_ROOT"]),"\\"),array('',"/"),realpath($this->cache_filename)));
		   exit;
		}
	}
  }
  //$content  内容
  public function create_cache($contents){
	if(!C("diy_cache")) return false;
	if(empty($contents))return false;
	if(!$this->cached){
	   $contents.="<!--created ".date("Y-m-d H:i:s")."-->";
	   @file_put_contents($this->cache_filename,$contents);	
	}
  }
}
/*使用范例*/
/*
import("ORG.Com.DiyCache");
$mycache=new DiyCache;
if(!$mycache->is_cached()){//处理自定义缓存
	//模板赋值
	if(C("diy_cache"))$mycache->create_cache($this->fetch());//创建缓存
	$this->display();
}
*/
/*使用范例*/
?>